package com.yifeng.repo.controller.postman.work.biz;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.yifeng.repo.base.utils.converter.JacksonHelper;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Created by daibing on 2023/5/24.
 */
public interface BizCallbackAction {

    /**
     * 业务回调动作标签：该参数将拼接到URI前缀后面，/开始，结束不带/，类似：/JuMengMessage/sendResultReceive
     */
    String tag();

    /**
     * 解析回调结果数据
     */
    default JsonNode parseCallbackResult(Map<String, String> callbackHeader, String callbackBody) {
        // 回调请求header中key都是小写
        String contentType = callbackHeader.get("content-type");
        if (contentType.startsWith(MediaType.APPLICATION_XML_VALUE)) {
            return xml2Obj(callbackBody);
        } else if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
            return JacksonHelper.toObj(callbackBody);
        } else {
            return JacksonHelper.createEmptyJsonNode();
        }
    }

    /**
     * 检查回调body
     */
    default boolean checkCallbackBody(JsonNode output) {
        return true;
    }

    /**
     * 检查回调签名
     */
    default boolean checkCallbackSign(JsonNode output) {
        return true;
    }

    /**
     * 保存回调数据
     */
    default String doSaveCallbackData(JsonNode output) {
        return null;
    }

    static JsonNode xml2Obj(String xml) {
        XmlMapper xmlMapper = new XmlMapper();
        try {
            return xmlMapper.readTree(xml.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
